package com.hsj.goldstore.base;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;

import com.hsj.goldstore.utils.ActivityCollector;
import com.hsj.goldstore.utils.Helper;

import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/3/21.
 */

public abstract class BaseMvpActivity<P extends IPresenter<V>, V extends BaseMvpView> extends AppCompatActivity implements BaseMvpView, LoaderManager.LoaderCallbacks<P> {

    private static final int BASE_LOAD_CODE = 1000;
    protected P presenter;
    private boolean isFirst = true;

    /**
     * @return 获取布局contentView
     */
    protected abstract int getResouseId();

    /**
     * 资源初始化，和事件绑定
     */
    protected abstract void initView();

    /**
     * 数据初始化
     */
    protected abstract void initData();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //隐藏软键盘
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        super.onCreate(savedInstanceState);
        setContentView(getResouseId());
        ButterKnife.bind(this);
        //初始化loader
        getSupportLoaderManager().initLoader(BASE_LOAD_CODE, null, this);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //view 与presenter绑定
        presenter.attachView((V) this);
        if (isFirst) {
            initView();
            initData();
            isFirst = false;
        }
    }


    @Override
    public void onLoadFinished(Loader<P> loader, P data) {
        presenter = data;
    }

    @Override
    public void onLoaderReset(Loader<P> loader) {
        presenter = null;
    }

    @Override
    public void showError(String err) {
        Helper.showToast(this, err);
    }

    @Override
    protected void onDestroy() {
        presenter.dettachView();
        super.onDestroy();
        ActivityCollector.removeActiivity(this);
    }
}
